import React, { useRef, FC, forwardRef, useImperativeHandle, useState, useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import TableDefined from '@/components/common/tableDefined'
import Dynamic from '@/api/dynamic'
import { modalLayoutSm } from '@/config/layout'
import { Button, Input, DatePicker, Select, Modal, Cascader,Spin, Upload, Table, Form, Steps, Row, Col, Tabs, Card, Radio, message } from 'antd';
import MyDefineSelect from '@/components/common/myDefineSelect'
import $axios from '@/utils/axios';
import { fn } from 'moment'
import DefineRdaio from './DefineRadio.tsx'
import DefineSelect from './DefineSelect.tsx'
import { MinusCircleOutlined, RightOutlined, PlusOutlined } from '@ant-design/icons';
const {Option} = Select;


const TableDefinedEdit = (props, refs) => {

    const [form] = Form.useForm()
    const [id,setid] = useState('');
    const { setFieldsValue, resetFields } = form
    const [columns,setcolumns] = useState([]);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [detailData,setdetailData] = useState({});
    let rule_fnValue = '';
    rule_fnValue = Form.useWatch('rule_fn', form);
    let  ruleParamsValue = Form.useWatch('rule_param', form);
    
    //清洗规则管理
    console.log(props.apiParamMng_id);
    useEffect(()=>{
      setdetailData({
        ...detailData,
        ...{
          ['rule_param']:typeof(ruleParamsValue)=='object'?JSON.stringify(ruleParamsValue):ruleParamsValue
        }
      })
    },[ruleParamsValue])
    useEffect(()=>{
        Dynamic.getDynamicQuery({
            apiID:props.apiID,
            apiParam:{
                api_id:props.apiParamMng_id
            }
        }).then((res)=>{
            let data = res.data;
            let apiParamStr = data.data['0']['api_param']?data.data['0']['api_param']:'';
            let  apiParam= data.data['0']['api_param']?JSON.parse(data.data['0']['api_param']):{};


            console.log(apiParam.paramList)
            let detailDataNew = {};
            apiParam.paramList.map((e)=>{
              detailDataNew[e.name] = '';
            })
            setdetailData(detailDataNew)
            setcolumns(apiParam.paramList)


        })


        // Dynamic.DynamicExecute({
        //   apiID:'DMT_MNG_02',
        //   apiParam:{
        //       // api_id:props.apiParamMng_id
        //   }
        //   }).then((res)=>{
        //   })
    },[])
    //显示弹窗
    const showModal = () => {
      setIsModalVisible(true);
    }; 

    //确定
    const handleOk = () => {
      form.validateFields().then((vals) => {
        let Obj = form.getFieldsValue()
        Obj = {
          ...Obj,
          ...detailData
        }
        let fn = id?$axios.put:$axios.post;
        let apiID = id?props.updateApiId:props.addApiId;
        let apiParam = {
          ...Obj
        }
        console.log(apiParam)
        if(id){
          apiParam['tran_task_id'] = id;
          apiParam['api_id'] = id;
          apiParam['pid'] = id;
          apiParam['load_task_id'] = id;
          apiParam['cap_task_id'] = id;
          apiParam['rule_id'] = id;
        }
        Dynamic.DynamicExecute({
          apiID:apiID,
          'apiParam':apiParam
        }) 
          .then((res) => {
            message.success('保存成功');
              handleCancel();
            })
            .catch((err) => {
            });
        // fn(url, Obj)
       
  
  
      }).catch(info => {
      })
    };
    //取消
    const handleCancel = () => {
      setIsModalVisible(false);
      setid('');
      resetFields();
      props.callback && props.callback();
    };
    useImperativeHandle(refs, () => ({
      init: (id) => {
        if(id){
          setid(id);
          getDetail(id);
        }else{
          resetFields();

          
          let detailDataNew = {
            ...detailData
          };
          for(let i in detailDataNew){
            detailDataNew[i] = '';
          }
          setdetailData(detailDataNew)
        }
        showModal();
        // setfileList([]);
      }
    }))
    const getDetail = (id)=>{
      Dynamic.getDynamicQuery({
        apiID:props.detailApiId,
        apiParam:{
          rule_id:id,
          tran_task_id:id,
          api_id:id,
          pid:id,
          load_task_id:id,
          cap_task_id:id
        }
      }).then((res)=>{
            let data = res['data']['data'][0];
            setdetailData(data);
            setTimeout(() => {
              window['setFieldsValue'] = setFieldsValue;
              setFieldsValue({
                ...data
              });
              if(props.apiParamMng_id=='DMT_A001_01'&&['map','replace'].indexOf(data.rule_fn)!=-1){
                try {
                  setFieldsValue({
                    'rule_param':JSON.parse(data.rule_param)
                  })
                } catch (error) {
                  
                }
               
                
              }
            }, 1000);
            
        // tableRef.current.update();
      })
      // $axios.get('/dm/api/metric/define/detail?measureCode='+id).then((res)=>{
      //   let data = res['data'];
      
      //   setFieldsValue({
      //     ...data
      //   });
      // })
    }
    
    return <Modal
      title={id === '' ? "新增" : '编辑'}
      visible={isModalVisible}
      onOk={handleOk}
      onCancel={handleCancel}
      centered={true}
      width={900}
      maskClosable={false}
      bodyStyle={{
        maxHeight: window.innerHeight - 150,
        overflowY: 'auto'
      }}
    >
      <Form form={form} {...modalLayoutSm}>
        {
            columns.map((e,i)=>{
                let item = e;
                let type = e['element']['type'];
                if(props.apiParamMng_id=='DMT_A001_01'&&['map','replace'].indexOf(rule_fnValue)!=-1&&item['name'] == 'rule_param'){
                  return <></>
                }
                return  <Form.Item
                name={item['name']}
                key={i}
                extra={item['element']['tip']||''}
                label={item['element']['label']}
                // label = {item['name']}
                rules={[{ required: item['element']['require'], message: type == 'radio'?'请选择'+item['element']['label']:'请输入'+item['element']['label'] }]}
            >
                {
                    type=='text'&&<Input value={detailData[item['name']]} onChange={(e)=>{
                        let name = item['name']
                        setFieldsValue({
                            [name]:e.target.value
                        })
                        setdetailData({
                          ...detailData,
                          ...{
                            [name]:e.target.value
                          }
                        })
                    }}/>
                }
                 {
                    type=='textarea'&&<Input.TextArea rows={item['element']['rows']||1} value={detailData[item['name']]}  onChange={(e)=>{
                        let name = item['name']
                        setFieldsValue({
                            [name]:e.target.value
                        })
                        setdetailData({
                          ...detailData,
                          ...{
                            [name]:e.target.value
                          }
                        })
                    }}/>
                }


{
                  (type == 'select'&&<div>
                    {
                      item?.element?.option_url?<DefineSelect value={detailData[item['name']]} onChange={(val)=>{
                        let name = item['name']
                        setFieldsValue({
                            [name]:val
                        })
                        setdetailData({
                          ...detailData,
                          ...{
                            [name]:val
                          }
                        })
                    }} {...item.element.option_url}/>:<Select value={detailData[item['name']]} onChange={(val)=>{
                        let name = item['name']
                        setFieldsValue({
                            [name]:val
                        })
                        setdetailData({
                          ...detailData,
                          ...{
                            [name]:val
                          }
                        })
                    }}>
                        {
                            item.element.option&&item.element.option.map((el,il)=>{
                                return <Option key={'kk'+il} value={el.value}>
                                    {el.label}
                              </Option>
                            })
                        }
                    </Select>
                    }

                  </div>)
                }
                {
                  (type == 'radio'&&<div>
                    {
                      item?.element?.option_url?<DefineRdaio value={detailData[item['name']]} onChange={(e)=>{
                        let name = item['name']
                        setFieldsValue({
                            [name]:e.target.value
                        })
                        setdetailData({
                          ...detailData,
                          ...{
                            [name]:e.target.value
                          }
                        })
                    }} {...item.element.option_url}/>:<Radio.Group value={detailData[item['name']]} onChange={(e)=>{
                        let name = item['name']
                        setFieldsValue({
                            [name]:e.target.value
                        })
                        setdetailData({
                          ...detailData,
                          ...{
                            [name]:e.target.value
                          }
                        })
                    }}>
                        {
                            item.element.option&&item.element.option.map((el,il)=>{
                                return <Radio key={'kk'+il} value={el.value}>
                                    {el.label}
                              </Radio>
                            })
                        }
                    </Radio.Group>
                    }

                  </div>)
                }
                 {
                    type=='password'&&<Input value={detailData[item['name']]} type='password' onChange={(e)=>{
                        let name = item['name']
                        setFieldsValue({
                            [name]:e.target.value
                        })
                        setdetailData({
                          ...detailData,
                          ...{
                            [name]:e.target.value
                          }
                        })
                    }}/>
                }
            </Form.Item>
            })
        }
      {
        props.apiParamMng_id=='DMT_A001_01'&&['map','replace'].indexOf(rule_fnValue)!=-1&&<Form.List
        name="rule_param"
      >
        {(fields, { add, remove }, { errors }) => (
          <>
            <Form.Item label="参数">
              {fields.map((field, index) => (
                <Row>
                  <Col span={10}>
                    <Form.Item name={[field.name, 'src']}>
                      <Input />
                    </Form.Item>
                  </Col>
                  <Col span={2}>
                    <div className='RightOutlinedWrap'>
                      <RightOutlined />
                    </div>

                  </Col>
                  <Col span={10}>
                    <Form.Item name={[field.name, 'target']}>
                      <Input />
                    </Form.Item>
                  </Col>
                </Row>

              ))}
              <Form.Item>
                <Button
                  type="dashed"
                  onClick={() => add()}
                  style={{ width: '60%' }}
                  icon={<PlusOutlined />}
                >
                  添加参数
                </Button>
              </Form.Item>
            </Form.Item>

          </>
        )}
      </Form.List>
        
        
        
       
      }
         {/* {
        props.apiParamMng_id=='DMT_A001_01'&& <Form.Item name='qxcs' label='清洗参数'>
          <Input.TextArea></Input.TextArea>
      </Form.Item>
        } */}
      </Form>
    </Modal>

}
const TableDefinedEditCom = forwardRef(TableDefinedEdit);


export default TableDefinedEditCom